# Simple MySQL Password Fix Script
Write-Host "Fixing MySQL password..." -ForegroundColor Green

# Stop MySQL service
Write-Host "Stopping MySQL service..." -ForegroundColor Yellow
Stop-Service mysql -Force
Start-Sleep -Seconds 5

# Create a temporary MySQL configuration file for safe mode
$tempConfig = @"
[mysqld]
skip-grant-tables
skip-networking
"@

$configPath = "C:\temp\my.ini"
New-Item -ItemType Directory -Path "C:\temp" -Force | Out-Null
$tempConfig | Out-File -FilePath $configPath -Encoding ASCII

# Start MySQL with the temporary config
Write-Host "Starting MySQL in safe mode..." -ForegroundColor Yellow

# Find MySQL installation
$possiblePaths = @(
  "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe",
  "C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe",
  "C:\ProgramData\chocolatey\lib\mysql\tools\mysqld.exe"
)

$mysqlPath = $null
foreach ($path in $possiblePaths) {
  if (Test-Path $path) {
    $mysqlPath = $path
    Write-Host "Found MySQL at: $mysqlPath" -ForegroundColor Green
    break
  }
}

if ($mysqlPath) {
  # Start MySQL in safe mode
  Start-Process -FilePath $mysqlPath -ArgumentList "--defaults-file=$configPath" -WindowStyle Hidden
    
  # Wait for MySQL to start
  Start-Sleep -Seconds 10
    
  # Find mysql client
  $mysqlClientPath = $mysqlPath -replace "mysqld.exe", "mysql.exe"
    
  if (Test-Path $mysqlClientPath) {
    Write-Host "Resetting root password..." -ForegroundColor Yellow
        
    # Reset password
    & $mysqlClientPath -u root -e "FLUSH PRIVILEGES;"
    & $mysqlClientPath -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'root123';"
    & $mysqlClientPath -u root -e "FLUSH PRIVILEGES;"
        
    Write-Host "Password reset completed!" -ForegroundColor Green
  }
  else {
    Write-Host "MySQL client not found at: $mysqlClientPath" -ForegroundColor Red
  }
    
  # Stop safe mode MySQL
  Get-Process mysqld -ErrorAction SilentlyContinue | Stop-Process -Force
  Start-Sleep -Seconds 5
    
  # Clean up temp config
  Remove-Item $configPath -Force -ErrorAction SilentlyContinue
    
  # Start MySQL service normally
  Write-Host "Starting MySQL service normally..." -ForegroundColor Yellow
  Start-Service mysql
    
}
else {
  Write-Host "MySQL installation not found!" -ForegroundColor Red
  Write-Host "Trying alternative approach..." -ForegroundColor Yellow
    
  # Alternative: Try to reset password using service restart
  Write-Host "Restarting MySQL service..." -ForegroundColor Yellow
  Start-Service mysql
}

Write-Host "MySQL password fix completed!" -ForegroundColor Green
Write-Host "Try connecting with:" -ForegroundColor Cyan
Write-Host "Username: root" -ForegroundColor White
Write-Host "Password: root123" -ForegroundColor White
